//
// Created by 29019 on 2019/12/21.
//

#ifndef GENERAL_OBSERVER_H
#define GENERAL_OBSERVER_H

#include <memory>
#include <vector>

template <typename  T> class Observer;

template <typename T> class Observed{
public:
    virtual  ~Observed(){};
    virtual  int AddObserver(Observer <T>*);     // 添加观察者
    virtual int DeleteObserver(Observer <T>*);   // 删除观察者
    virtual int NoticeObserver(T *);
protected:
    std::vector<Observer <T>*> m_vObservers;
};

template <typename  T>class Observer
{
public:
    virtual void OnNotifyData(T* ){};
private:

};

template<typename T>
int Observed<T>::AddObserver(Observer<T> *p) {
    if(nullptr == p){
        return -1;
    }

    for(typename std::vector<Observer<T>*>::iterator itr = m_vObservers.begin();
        itr != m_vObservers.end();itr++){
        if(((Observer<T>*)*itr) == p){
            return 0;
        }
    }
    this->m_vObservers.push_back(p);
    return 0;
}

template<typename T>
int Observed<T>::DeleteObserver(Observer<T> *p) {
    for(typename  std::vector<Observer<T>*>::iterator itr = m_vObservers.begin();
        itr != m_vObservers.end();itr++){
        if(((Observer<T>*)*itr) == p){
            return 0;
        }
    }
    return 0;
}
template<typename T>
int Observed<T>::NoticeObserver(T *p) {
    if(nullptr == p){
        return  -1;
    }
    for(typename  std::vector<Observer<T>*>::iterator itr = m_vObservers.begin();
        itr != m_vObservers.end();itr++){
        ((Observer<T>*)*itr)->OnNotifyData(p);
    }
    return 0;
}

#endif //GENERAL_OBSERVER_H
